package Concurrent.threadsafety.services;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author yichangkong
 * @create 2020-08-10-22:30
 */
public class ReentrantReadWriteLockCounter {
    private int counter;
    private final ReentrantReadWriteLock rwLock= new ReentrantReadWriteLock();
    private final Lock readLock= rwLock.readLock();
    private final Lock writeLock= rwLock.writeLock();

    public ReentrantReadWriteLockCounter( ) {
        this.counter = 0;
    }
    public void incrementCounter(){
        writeLock.lock();
        try{
            counter +=1;
        }finally{
            writeLock.unlock();
        }
    }

    public int getCounter() {
        readLock.lock();
        try{
            return counter;
        }finally{
            readLock.unlock();
        }

    }
}
